package thread.lockpackage;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author ch
 * <p>
 * 使用ReentrantLock实现线程间通讯
 */
public class MyLockCondition {

    private final Lock lock = new ReentrantLock();
    private final Condition conditionA = lock.newCondition();
    private final Condition conditionB = lock.newCondition();

    public static void main(String[] args) {
        try {
            MyLockCondition myLockCondition = new MyLockCondition();
            //new Thread(() -> lockCondition.await(lockCondition.conditionA), "thread1_conditionA").start();
            new Thread(() -> myLockCondition.myAwait(myLockCondition.conditionB), "thread2_conditionB").start();
            /*new Thread(() -> lockCondition.signal(lockCondition.conditionA), "thread3_conditionA").start();
            System.out.println("稍等5秒在通知其他线程");
            Thread.sleep(5000);*/
            new Thread(() -> myLockCondition.mySignal(myLockCondition.conditionB), "thread4_conditionB").start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void myAwait(Condition condition) {
        try {
            lock.lock();
            System.out.println("即将放弃lock锁！thread：" + Thread.currentThread().getName());
            condition.await();// 释放lock锁，停在这
            System.out.println("重新获取lock锁！thread：" + Thread.currentThread().getName());
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    private void mySignal(Condition condition) {
        lock.lock();
        System.out.println("发送通知signal：thread：" + Thread.currentThread().getName());
        condition.signal();
        System.out.println("发送完通知signal：thread：" + Thread.currentThread().getName());
        lock.unlock();
    }

}
